package com.edu.juc.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 阻塞的方式和异步编程的设计理念相违背，而轮询的方式会耗费无谓的CPU资源。
 * CompletableFuture提供了一种观察者模式类似的机制，可以让任务执行完成后通知监听的一方。
 */
public class CompletableFutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        public static CompletableFuture<Void> runAsync(Runnable runnable);
//        public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);                Executor executor)
        // 异步调用 无返回值
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
        });
        System.out.println(voidCompletableFuture.get());

//        public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
//        public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);
        // 异步调用 有返回值
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
            return 1;
        });

        Integer integer = future.get();
        System.out.println("integer = " + integer);

        ExecutorService service = Executors.newFixedThreadPool(10);
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
            return 1;
        }, service);

        Integer integer1 = future1.get();
        System.out.println("integer1 = " + integer1);


        service.shutdown();

    }
}
